import java.util.LinkedList;

/**
 * @author liuchun
 * 创建蛇身
 */
public class Snake {
    //蛇身
    private LinkedList<Node> body;

   //标记蛇是否存活
    public boolean isLive = true;
   //蛇的移动方向
    private Direction direction = Direction.RIGHT ;

   //创建蛇对象时，初始化蛇身
    public Snake(){
        initSnake();
    }
    //判断蛇是否触壁
    public void checkOver(){
        Node head = body.getFirst();
        int x = head.getX();
        int y = head.getY();
        if (x < 0 || y< 0 || x >= 40 || y >= 40){
            isLive = false;
        }
    }

    //初始化蛇身
    private void initSnake() {
        //创建蛇的躯体
        body = new LinkedList<Node>();
        //给蛇添加三个节点，在棋盘的中心位置横向排列
        body.add(new Node(15,15));
        body.add(new Node(16,15));
        body.add(new Node(17,15));
    }

    //获取蛇的身体
    public LinkedList<Node> getBody() {
        return body;
    }

    public void setDirection(Direction direction){
        this.direction = direction;
    }
    //移动方法
    public void move(){
        //获取蛇的头结点
        Node head = body.getFirst();
        //新的蛇头结点
        Node newHead = null;
        switch (direction){
            //向左移动
            case LEFT:
                newHead = new Node(head.getX()-1,head.getY());
                //添加为头结点
                body.addFirst(newHead);
                //删除尾节点
                body.removeLast();
                break;
            //向上移动
            case UP:
                newHead = new Node(head.getX(),head.getY()-1);
                //添加为头结点
                body.addFirst(newHead);
                //删除尾节点
                body.removeLast();
                break;
            case DOWN:
                newHead = new Node(head.getX(),head.getY() +1);
                //添加为头结点
                body.addFirst(newHead);
                //删除尾节点
                body.removeLast();
                break;
            case RIGHT:
                newHead = new Node(head.getX()+1,head.getY());
                //添加为头结点
                body.addFirst(newHead);
                //删除尾节点
                body.removeLast();
                break;
        }
    }

}
